#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time: 2023/1/5 0:47
# @Author: 周阳
# @Email: 100530987@qq.com
# @File：mail.py
import smtplib
import os
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from config.config import Config
from common.consts import REPORT_PATH
from common.log import Log

c= Config()
logger = Log.get_logger()

def send_email(report):
    c = Config()

    #创建邮件对象
    msg = MIMEMultipart()
    #配置email头
    msg["Subject"] = c.get_email("subject")
    msg["From"] = c.get_email("user")
    msg["To"] = c.get_email("receiver")
    #格式化email正文，同时将报告以附件的形式发送
    with open(os.path.join(REPORT_PATH, report), "rb") as f:
        body = f.read()
    attach = MIMEBase('zip', 'zip', filename=report)
    #给附件重命名，一般和源文件一样
    attach.add_header('Content-Disposition', 'attachment', filename=('gb2312', '', report))
    attach.set_payload(body)
    encoders.encode_base64(attach)
    msg.attach(attach)
    smtp = smtplib.SMTP()
    try:
        #连接smtp服务器发送邮件
        smtp.connect(c.get_email("server"))
        smtp.login(c.get_email("user"), c.get_email("pwd"))
        smtp.sendmail(c.get_email("user"), c.get_email("receiver"), msg.as_string())
    except Exception as e:
        print(e)
        print("发送失败")
        logger.error("邮件发送失败,请检查邮件配置")
    else:
        print("发送成功")
        logger.info("邮件发送成功")
    finally:
        smtp.quit()
if __name__ == '__main__':  # 验证发送邮件
    from common.consts import CASE_PATH
    xx = os.path.join(CASE_PATH, 'test_login_Memberstatus.py')
    send_email(xx)